// OpenID缓存测试
// 测试OpenID缓存机制是否正确工作，防止房间加入bug

import CloudManager from '../network/cloudManager.js'

class OpenIdCacheTest {
  constructor() {
    this.cloudManager = new CloudManager()
    this.testResults = []
  }

  // 测试OpenID缓存机制
  async testOpenIdCaching() {
    console.log('🧪 开始测试OpenID缓存机制...')
    
    try {
      // 第一次获取OpenID
      const openId1 = await this.cloudManager.getOpenId()
      console.log('第一次获取OpenID:', openId1)
      
      // 第二次获取OpenID（应该返回相同的ID）
      const openId2 = await this.cloudManager.getOpenId()
      console.log('第二次获取OpenID:', openId2)
      
      // 验证两次获取的OpenID相同
      if (openId1 === openId2) {
        console.log('✅ OpenID缓存测试通过：两次获取的ID相同')
        this.testResults.push({ test: 'OpenID缓存', result: 'PASS' })
      } else {
        console.log('❌ OpenID缓存测试失败：两次获取的ID不同')
        this.testResults.push({ test: 'OpenID缓存', result: 'FAIL', details: `${openId1} !== ${openId2}` })
      }
      
      // 清理后再次获取（应该返回新的ID）
      this.cloudManager.cleanup()
      const openId3 = await this.cloudManager.getOpenId()
      console.log('清理后获取OpenID:', openId3)
      
      if (openId3 !== openId1) {
        console.log('✅ OpenID清理测试通过：清理后获取了新的ID')
        this.testResults.push({ test: 'OpenID清理', result: 'PASS' })
      } else {
        console.log('❌ OpenID清理测试失败：清理后ID未改变')
        this.testResults.push({ test: 'OpenID清理', result: 'FAIL', details: `${openId3} === ${openId1}` })
      }
      
    } catch (error) {
      console.error('OpenID缓存测试出错:', error)
      this.testResults.push({ test: 'OpenID缓存', result: 'ERROR', details: error.message })
    }
  }

  // 测试房间创建和加入的OpenID一致性
  async testRoomOpenIdConsistency() {
    console.log('🧪 开始测试房间创建和加入的OpenID一致性...')
    
    try {
      // 模拟创建房间
      const createOpenId = await this.cloudManager.getOpenId()
      console.log('创建房间使用的OpenID:', createOpenId)
      
      // 模拟加入房间（使用相同的cloudManager实例）
      const joinOpenId = await this.cloudManager.getOpenId()
      console.log('加入房间使用的OpenID:', joinOpenId)
      
      if (createOpenId === joinOpenId) {
        console.log('✅ 房间OpenID一致性测试通过：创建和加入使用相同ID')
        this.testResults.push({ test: '房间OpenID一致性', result: 'PASS' })
      } else {
        console.log('❌ 房间OpenID一致性测试失败：创建和加入使用不同ID')
        this.testResults.push({ test: '房间OpenID一致性', result: 'FAIL', details: `${createOpenId} !== ${joinOpenId}` })
      }
      
    } catch (error) {
      console.error('房间OpenID一致性测试出错:', error)
      this.testResults.push({ test: '房间OpenID一致性', result: 'ERROR', details: error.message })
    }
  }

  // 测试防止自己加入自己房间的逻辑
  async testSelfJoinPrevention() {
    console.log('🧪 开始测试防止自己加入自己房间的逻辑...')
    
    try {
      const openId = await this.cloudManager.getOpenId()
      console.log('当前用户OpenID:', openId)
      
      // 模拟房间数据
      const mockRoom = {
        player1: openId,
        status: 'waiting'
      }
      
      // 模拟检查逻辑
      const canJoin = mockRoom.player1 !== openId
      
      if (!canJoin) {
        console.log('✅ 防止自己加入自己房间测试通过：正确阻止了自己加入')
        this.testResults.push({ test: '防止自己加入', result: 'PASS' })
      } else {
        console.log('❌ 防止自己加入自己房间测试失败：错误地允许了自己加入')
        this.testResults.push({ test: '防止自己加入', result: 'FAIL', details: 'OpenID检查逻辑错误' })
      }
      
    } catch (error) {
      console.error('防止自己加入自己房间测试出错:', error)
      this.testResults.push({ test: '防止自己加入', result: 'ERROR', details: error.message })
    }
  }

  // 运行所有测试
  async runAllTests() {
    console.log('🚀 开始运行OpenID缓存相关测试...')
    
    await this.testOpenIdCaching()
    await this.testRoomOpenIdConsistency()
    await this.testSelfJoinPrevention()
    
    this.printResults()
  }

  // 打印测试结果
  printResults() {
    console.log('\n📊 测试结果汇总:')
    console.log('=' * 50)
    
    let passCount = 0
    let failCount = 0
    let errorCount = 0
    
    this.testResults.forEach(result => {
      const status = result.result === 'PASS' ? '✅' : result.result === 'FAIL' ? '❌' : '⚠️'
      console.log(`${status} ${result.test}: ${result.result}`)
      
      if (result.details) {
        console.log(`   详情: ${result.details}`)
      }
      
      if (result.result === 'PASS') passCount++
      else if (result.result === 'FAIL') failCount++
      else errorCount++
    })
    
    console.log('\n📈 统计:')
    console.log(`通过: ${passCount}`)
    console.log(`失败: ${failCount}`)
    console.log(`错误: ${errorCount}`)
    console.log(`总计: ${this.testResults.length}`)
    
    if (failCount === 0 && errorCount === 0) {
      console.log('\n🎉 所有测试通过！OpenID缓存机制工作正常。')
    } else {
      console.log('\n⚠️ 部分测试失败，需要进一步检查。')
    }
  }
}

// 如果直接运行此文件
if (typeof window === 'undefined') {
  const test = new OpenIdCacheTest()
  test.runAllTests()
}

export default OpenIdCacheTest 